import React, { Component } from 'react'
import { Form, Button, Card, Checkbox, message, Spin } from 'antd'

import { address } from '@/Utils/apiConfig'
import getData from '@/Utils/fecth'

import './addNode.less'

const { leagueManagement: { addNodeToOrg, getNodesOfChannel }} = address
const FormItem = Form.Item
const CheckboxGroup = Checkbox.Group

class AddNode extends Component {
  constructor(props) {
    super(props)
    this.state = {
      checkedList: [],
      indeterminate: false,
      checkAll: false,
      initialValues: {
        options: [],
      },
      loading: false,
      nodeList: [],
      nodeIds: [],
      channelName: props.match.params.channelName,
      channelId: props.match.params.channelId,
      consortiumId: props.match.params.id,
      peerName: props.match.params.peerName,
      peerId: props.match.params.peerId,
    }
  }

  formRef = React.createRef();

  componentDidMount() {
    this.getNodeOfChannel()
  }

  getNodeOfChannel = async() => {
    const { consortiumId, channelId, peerId } = this.state
    let nodeList = null
    let nodeIds = null
    await getData().get(getNodesOfChannel.format({ consortiumId, channelId, peerId })).then(res => {
      switch (res.status) {
      case 200:
        nodeList = res.data
        nodeIds = nodeList.map(item => { return item.id })
        this.setState({
          nodeList,
          nodeIds,
          loading: false,
        })
        break
      default:
        message.error('请求失败')
        break
      }
    })
    return nodeList
  }

  onChange = checkedList => {
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < this.state.nodeIds.length,
      checkAll: checkedList.length === this.state.nodeIds.length,
    })
  };

  onCheckAllChange = e => {
    this.formRef.current.setFieldsValue({
      options: e.target.checked ? this.state.nodeIds : [],
    })
    this.setState({
      checkedList: e.target.checked ? this.state.nodeIds : [],
      indeterminate: false,
      checkAll: e.target.checked,
    })
  };

  onFinish = async(values) => {
    const { checkedList, consortiumId, channelId } = this.state
    let params = {
      nodeIds: checkedList,
    }
    this.setState({
      loading: true,
    })
    let res = await getData().post(addNodeToOrg.format({ consortiumId, channelId }), params)
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      message.success('节点添加中')
      this.props.history.goBack()
    } else {
      message.error('添加失败')
    }
  }

  // toCreateNewNode = () => {
  // 	this.props.history.push({ pathname: `/dashboard/fabric/organizationInfo/${this.state.peerId}/createPeer` })
  // }

  renderForm = () => {
    const { initialValues, nodeList, channelName, peerName } = this.state
    const layout = {
      labelCol: { span: 2 },
      wrapperCol: { span: 10 },
    }
    const tailLayout = {
      wrapperCol: { offset: 2, span: 10 },
    }
    return (
      <Form ref={this.formRef} initialValues={initialValues} hideRequiredMark onFinish={this.onFinish}>
        <FormItem {...layout} label="通道名称" >
          {channelName}
        </FormItem>
        <FormItem {...layout} label="组织名称" >
          {peerName}
        </FormItem>
        <FormItem {...layout} label="选择节点" rules={[{ required: true }]}>
          <Card bordered={false} bodyStyle={{ padding: '0' }} >
            <FormItem noStyle>
              <Checkbox
                style={{ lineHeight: '35px' }}
                indeterminate={this.state.indeterminate}
                onChange={this.onCheckAllChange}
                checked={this.state.checkAll}
              >
                全选
		            </Checkbox>
            </FormItem>
            <FormItem name="options" rules={[{ required: true, message: '请选择节点' }]} noStyle>
              <CheckboxGroup style={{ width: '100%', background: '#ffffff' }} onChange={this.onChange} >
                {nodeList.map((item) => {
                  return (
                    <Checkbox
                      key={item.id}
                      style={{ lineHeight: '35px' }}
                      value={item.id}
                    >
                      {item.name}
                    </Checkbox>
                  )
                })}
              </CheckboxGroup>
            </FormItem>
            {/* <FormItem noStyle>
									<Button
										style={{paddingLeft: 44}}
										type="link"
										onClick={() => this.toCreateNewNode()}
									>
										+创建新节点
									</Button>
								</FormItem> */}
          </Card>
        </FormItem>
        <FormItem {...tailLayout} >
          <Button type="primary" htmlType="submit">
            提交
		        </Button>
          <Button style={{ marginLeft: 8 }} onClick={() => { this.props.history.goBack() }} disabled={this.state.cancelDisabled}>
            取消
		        </Button>
        </FormItem>
      </Form>
    )
  }

  renderNoNode = () => {
    return (
      <div className="invite-box empty">
        <img width={112} src={require('@/images/fabric/1.svg')} alt="" />
        <div className="empty-go">
          <span>暂时还没有节点</span>
          {/* <span style={{cursor:'pointer'}} onClick={()=>{this.toCreateNewNode()}}>去创建</span> */}
        </div>
      </div>
    )
  }

  render() {
    const { nodeList, channelName } = this.state
    return (
      <Spin spinning={this.state.loading}>
        <Card className="join-channel-box common">
          {nodeList.length ? '' : <h1 className="invite-title">{`请选择需要添加到通道"${channelName}"的节点`}</h1>}
          {
            nodeList.length ? this.renderForm() : this.renderNoNode()
          }
        </Card>
      </Spin>
    )
  }
}

export default AddNode
